<template>
    <div style="display: flex; flex-flow: row;justify-content: space-between;align-items: center;">
        <a-breadcrumb style="margin: 16px 0">
            <a-breadcrumb-item>菜品管理</a-breadcrumb-item>
        </a-breadcrumb>
        <div>
            <a-input 
                v-model:value="searchName" 
                placeholder="搜索菜品" 
                style="width: 200px;margin: 0 10px;" 
                @input="handleSearchChange"
                enter_button/>
            <a-select 
                v-model:value="selectedType" 
                style="width: 100px;justify-content: space-between;margin: 0 10px;" 
                placeholder="选择类别"
                @change="handleTypeChange"
            >
                <a-select-option value="">全部类别</a-select-option>
                <a-select-option value="川菜">川菜</a-select-option>
                <a-select-option value="鲁菜">鲁菜</a-select-option>
                <a-select-option value="湘菜">湘菜</a-select-option>
                <a-select-option value="粤菜">粤菜</a-select-option>
                <a-select-option value="家常菜">家常菜</a-select-option>
                <a-select-option value="主食">主食</a-select-option>
                <a-select-option value="蒸菜">蒸菜</a-select-option>
                <a-select-option value="汤">汤</a-select-option>
                <a-select-option value="饮料">饮料</a-select-option>
                <a-select-option value="海鲜">海鲜</a-select-option>
            </a-select>
            <a-select 
                v-model:value="selectedStatus" 
                style="width: 100px;justify-content: space-between;margin: 0 10px;" 
                placeholder="选择状态"
                @change="handleStatusChange"
            >
                <a-select-option value="">全部状态</a-select-option>
                <a-select-option value="1">上架中</a-select-option>
                <a-select-option value="0">下架中</a-select-option>
            </a-select>
            <a-button type="primary" @click="showModal">添加菜品</a-button>
        </div>
    </div>

    <div :style="{ padding: '24px', background: '#fff', minHeight: '360px' }">
        <!-- 菜品内容表格 -->
        <a-table :columns="columns" :data-source="filteredData">
            <template #headerCell="{ column }">
                <template v-if="column.key === 'name'">
                    <span>
                        <smile-outlined />
                        菜品名
                    </span>
                </template>
            </template>

            <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'name'">
                    <a>{{ record.name }}</a>
                </template>
                <template v-else-if="column.key === 'action'">
                    <span>
                        <a @click="showupdate(record)">修改</a>
                        <a-divider type="vertical" />
                        <a @click="deleteDish(record.id)">删除</a>
                        <a-divider type="vertical" />
                        <a-button 
                            :style="{ backgroundColor: record.status === 0 ? 'white' : '#f50' }"
                            @click="toggleDishStatus(record.id, record.status)">
                            {{ record.status === 0 ? '上架' : '停售' }}
                        </a-button>
                    </span>
                </template>
                <!-- 时间格式化列 -->
                <template v-else-if="column.dataIndex === 'createTime'">
                    {{ formatDate(record.createTime) }}
                </template>
                <!-- 状态格式化列 -->
                <template v-else-if="column.dataIndex === 'status'">
                    {{ record.status === 1 ? '上架中' : '下架中' }}
                </template>
                
            </template>
        </a-table>
    </div>

    <!-- 新增菜品弹窗 -->
    <a-modal v-model:open="modalVisible" title="添加菜品" centered @ok="onSubmit">
        <a-form :model="dish" :label-col="labelCol" :wrapper-col="wrapperCol">
            <a-form-item label="菜品名称">
                <a-input v-model:value="dish.name" />
            </a-form-item>
            <a-form-item label="菜品类别">
                <a-select v-model:value="dish.type">
                    <a-select-option value="川菜">川菜</a-select-option>
                    <a-select-option value="鲁菜">鲁菜</a-select-option>
                    <a-select-option value="湘菜">湘菜</a-select-option>
                    <a-select-option value="粤菜">粤菜</a-select-option>
                    <a-select-option value="家常菜">家常菜</a-select-option>
                    <a-select-option value="主食">主食</a-select-option>
                    <a-select-option value="蒸菜">蒸菜</a-select-option>
                    <a-select-option value="汤">汤</a-select-option>
                    <a-select-option value="饮料">饮料</a-select-option>
                    <a-select-option value="海鲜">海鲜</a-select-option>
                </a-select>
            </a-form-item>
            <a-form-item label="价格">
                <a-input v-model:value="dish.price" />
            </a-form-item>
            <a-form-item label="描述">
                <a-textarea v-model:value="dish.desc" autoSize="true" />
            </a-form-item>
        </a-form>
    </a-modal>
    <!-- 修改菜品弹窗 -->
    <a-modal v-model:open="updateVisible" title="修改菜品" centered @ok="updateDish">
        <a-form :model="dish" :label-col="labelCol" :wrapper-col="wrapperCol">
            <a-form-item label="菜品名称">
                <a-input v-model:value="dish.name" />
            </a-form-item>
            <a-form-item label="价格">
                <a-input v-model:value="dish.price" />
            </a-form-item>
            <a-form-item label="描述">
                <a-textarea v-model:value="dish.desc" autoSize="true" />
            </a-form-item>
        </a-form>
    </a-modal>
</template>

<script lang="ts" setup>
import dayjs from 'dayjs';
import { SmileOutlined } from '@ant-design/icons-vue';
import { message, TablePaginationConfig } from 'ant-design-vue';
import { onMounted, reactive, ref } from 'vue';
import { DishData } from '@/type/dish';
import DishDao from '@/daos/dish_dao';
import { update } from 'lodash';
import { color } from 'echarts';

const dishDao = new DishDao();

// 定义表格列
const columns = [
    {
        title: '菜品名',
        dataIndex: 'name',
        key: 'name',
        align: 'center' as const,
        width: 100
    },
    {
        title: '价格',
        dataIndex: 'price',
        key: 'price',
        align: 'center' as const,
        width: 50
    },
    {
        title: '描述',
        dataIndex: 'description',
        key: 'description',
        align: 'center' as const,
        width: 250
    },
    {
        title: '类型',
        dataIndex: 'type',
        key: 'type',
        align: 'center' as const,
        width: 50
    },
    {
        title: '状态',
        dataIndex: 'status',
        key:'status',
        align: 'center' as const,
        width: 50
    },
    {
        title: '上架时间',
        dataIndex: 'createTime',
        key: 'createTime',
        align: 'center' as const,
        width: 100
    },
    {
        title: '操作',
        key: 'action',
        align: 'center' as const,
        width: 80
    },
];

// 定义菜品数据
const data = ref([]);
const modalVisible = ref<boolean>(false);
const updateVisible = ref<boolean>(false);
const dish = reactive<DishData>({
    Id: undefined,
    name: '',
    type: '',
    price: 1,
    desc: '',
    status: 0,
});

// 筛选状态
const selectedType = ref('');
const selectedStatus = ref('');
const searchName = ref('');

// 筛选数据
const filteredData = ref([]);

// 新增弹窗的参数
const labelCol = { style: { width: '100px' } };
const wrapperCol = { style: { width: '250px' }, span: 14 };

// 初始化数据
onMounted(() => {
    init();
});

const init = async () => {
    let result = await dishDao.listAll();
    result.data.data.forEach((element: any) => {
        element.key = element.id.toString();
        element.price = element.price / 100;
        element.name = element.name || '';
        element.type = element.type || '';
        element.description = element.description || '';
        element.createTime = new Date(element.createTime); // 确保createTime字段正确
        element.status = element.status || 0; // 确保status字段正确
    });
    data.value = result.data.data;
    loadFilteredData(); // 初始化时加载筛选数据
};

// 删除菜品
const deleteDish = async (dishId: number) => {
    let result = await dishDao.deleteDish(dishId);
    if (result.data.code === 200) {
        message.info(result.data.data);
        loadFilteredData(); // 删除后重新加载筛选数据
    } else {
        message.error(result.data.msg);
    }
};

// 提交新增菜品
const onSubmit = async () => {
    try {
        let result = await dishDao.saveDish(dish);
        if (result.data.code === 200) {
            message.info(result.data.data);
            loadFilteredData(); // 新增后重新加载筛选数据
            modalVisible.value = false;
        } else {
            message.error(result.data.msg);
            modalVisible.value = false;
        }
    } catch (error) {
        message.error("请求错误");
    }
};

//提交修改菜品
const updateDish = async () => {
    try {
        let result = await dishDao.updateDish(dish);
        console.log(result);
        if (result.data.code === 200) {
            message.info(result.data.data);
            loadFilteredData(); // 修改后重新加载筛选数据
            updateVisible.value = false;
        } else {
            message.error(result.data.msg);
            updateVisible.value = false;
        }
    } catch (error) {
        message.error("请求错误");
    }
};

// 显示新增菜品弹窗
const showModal = () => {
    modalVisible.value = true;
     // 重置dish数据
    dish.Id = undefined;
    dish.name = '';
    dish.type = '';
    dish.price = 1;
    dish.desc = '';
    dish.status = 0;
};

// 显示修改菜品弹窗
const showupdate = (record: any) => {
    updateVisible.value = true;
    dish.Id = record.id;
    dish.name = record.name
    dish.price = record.price
    dish.desc = record.description;
    dish.status = record.status;
    console.log(record);
    Object.assign(dish, record);
};

// 切换菜品状态
const toggleDishStatus = async (dishId: number, currentStatus: number) => {
    try {
        const newStatus = currentStatus === 0 ? 1 : 0; // 切换状态
        console.log(dishId, newStatus);
        let result = await dishDao.updateDishStatus(dishId, newStatus);
        console.log(result);
        if (result.data.code === 200) {
            message.info(result.data.data);
            loadFilteredData(); // 状态切换后重新加载筛选数据
        } else {
            message.error(result.data.msg);
        }
    } catch (error) {
        message.error("请求错误");
    }
};

// 处理类别筛选变化
const handleTypeChange = () => {
    loadFilteredData();
};

// 处理状态筛选变化
const handleStatusChange = () => {
    loadFilteredData();
};

const handleSearchChange = () => {
    console.log("搜索数据：",searchName.value);
    loadFilteredData();
};

// 加载筛选后的数据
const loadFilteredData = async () => {
    try {
        // 如果都选择了"全部"，则显示所有数据
        console.log("筛选数据：",selectedType.value, selectedStatus.value,searchName.value);
        if (selectedType.value === '' && selectedStatus.value === '' && searchName.value === '') {
            let result = await dishDao.listAll();
            if (result.data.code === 200) {
                result.data.data.forEach((element: any) => {
                    element.key = element.id.toString();
                    element.price = element.price / 100;
                    element.name = element.name || '';
                    element.type = element.type || '';
                    element.description = element.description || '';
                    element.createTime = new Date(element.createTime);
                    element.status = element.status || 0;
                });
                filteredData.value = result.data.data;
            } else {
                message.error(result.data.msg);
            }
        } else {
            // 否则调用筛选API
            const type = selectedType.value || undefined;// 菜品类别筛选
            const status = selectedStatus.value ? parseInt(selectedStatus.value) : undefined;// 菜品状态筛选
            const name = searchName.value || undefined;
        
            
            let result = await dishDao.listByTypeAndStatus(type, status,name);
            // console.log(result.data);
             console.log(result.data.data);
            if (result.data.code === 200) {
                result.data.data.forEach((element: any) => {
                    element.key = element.id.toString();
                    element.price = element.price / 100;
                    element.name = element.name || '';
                    element.type = element.type || '';
                    element.description = element.description || '';
                    element.createTime = new Date(element.createTime);
                    console.log(element.createTime)
                    element.status = element.status || 0;
                });
                filteredData.value = result.data.data;
            } else {
                message.error(result.data.msg);
            }
        }
    } catch (error) {
        message.error("请求错误，或没有符合的菜品");
    }
};

// 应用筛选（前端筛选方法，作为备用）
const applyFilters = () => {
    filteredData.value = data.value.filter(item => {
        const matchesType = selectedType.value === '' || item.type === selectedType.value;
        const matchesStatus = selectedStatus.value === '' || item.status === parseInt(selectedStatus.value);
        return matchesType && matchesStatus;
    });
};



// 格式化日期
const formatDate = (date: Date) => {
    return dayjs(date).format('YYYY-MM-DD HH:mm:ss');
};
</script>